package wymiana.service;

import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import wymiana.dao.GroupDao;
import wymiana.domain.DGroup;
import wymiana.domain.User;

@Service("groupService")
@Transactional
public class GroupService {

	@Autowired
	private GroupDao groupDao;

	public void create(DGroup person) {
		groupDao.save(person);
	}

	public List<DGroup> getAllGroups() {
		List<DGroup> gr = groupDao.getAll();
		if (gr != null) {
			for (DGroup g : gr) {
				Hibernate.initialize(g.getDepartment());
				Hibernate.initialize(g.getDepartment().getSchool());
				Hibernate.initialize(g.getUploadedFiles());
				Hibernate.initialize(g.getUsers());
				Hibernate.initialize(g.getCreateUser());
			}
		}
		return gr;
	}

	public DGroup getGroup(int p_id) {
		DGroup g = groupDao.getGroupById(p_id);
		try {
			Hibernate.initialize(g.getDepartment());
			Hibernate.initialize(g.getDepartment().getSchool());
			Hibernate.initialize(g.getUploadedFiles());
			Hibernate.initialize(g.getUsers());
			Hibernate.initialize(g.getCreateUser());
		} catch (Exception e) {

		}
		return g;
	}

	public List<DGroup> getMyGroups(User u) {
		List<DGroup> gr = groupDao.getMyGroup(u);
		if (gr != null) {
			for (DGroup g : gr) {
				Hibernate.initialize(g.getDepartment());
				Hibernate.initialize(g.getDepartment().getSchool());
				Hibernate.initialize(g.getUploadedFiles());
				Hibernate.initialize(g.getUsers());
				Hibernate.initialize(g.getCreateUser());
			}
		}
		
		return gr;
	}

	public void updateGroup(DGroup p) {
		groupDao.merge(p);
	}

	public void deleteGroupById(int g_id) {
		DGroup g = groupDao.getById(g_id);
		groupDao.delete(g);
	}
}
